package com.xmy.cultivate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xmy.cultivate.characteristic.Characteristic;
import com.xmy.cultivate.characteristic.TrackCharacteristic;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.IFincTypeScopeService;
import com.xmy.cultivate.service.IFincTypeService;
import com.xmy.cultivate.service.IStaffService;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.IdWorker;
import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 财务费用类型 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2025-05-17
 */
@RestController
@RequestMapping("/api/admin/fincType")
public class FincTypeController extends BaseController{

    @Autowired
    IFincTypeService iFincTypeService;
    @Resource
    Characteristic characteristic;

    @Autowired
    IdWorker idWorker;

    @Autowired
    IFincTypeScopeService iFincTypeScopeService;

    @Autowired
    IStaffService iStaffService;


    @GetMapping("/fincTypeList")
    public Result fincTypeList(@RequestParam Map<String, String> reMap) {
        IPage<FincType> iPage = characteristic.findAll(reMap);
        return new Result(Code.GET_OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    @GetMapping("")
    public Result fincType(@RequestParam(value = "type", defaultValue = "0") String type,  //0支出类型   1子支出类型
                           @RequestParam(value = "id",defaultValue = "",required = false) String id
                       ) {
        QueryWrapper<FincType> queryWrapper = new QueryWrapper<>();
        if (type.equals("0")) {
            queryWrapper.eq("pid", 0);
        } else if (type.equals("1") && id != null) {
            queryWrapper.eq("pid", id);
        }
        List<FincType> list = iFincTypeService.list(queryWrapper);
        return new Result(Code.GET_OK, list, Code.GET_OK_MSG);
    }




    /**
     * 添加
     * @param fincType
     * @return
     */
    @PostMapping("/addFincType")
    public Result addFincType(@RequestBody FincType fincType) {
//        if (fincType.getId() == null) {
            fincType.setType(2);  //支出
            boolean save = iFincTypeService.save(fincType);
            if (save) {
                return new Result(Code.OK, null, "添加成功");
            } else {
                return new Result(Code.ERROR, null, "添加失败");
            }
//        } else {
//            FincType fincType1 = iFincTypeService.getById(fincType.getId());
//            if (fincType1 == null){
//                return new Result(Code.ERROR, null, "不存在该数据，编辑失败");
//            }
//            boolean update = iFincTypeService.updateById(fincType);
//            if (update) {
//                return new Result(Code.OK, null, "编辑成功");
//            } else {
//                return new Result(Code.ERROR, null, "编辑失败");
//            }
//        }
    }

    @PutMapping("/editFincType")
    public Result editFincType(@RequestBody FincType fincType) {
        FincType fincType1 = iFincTypeService.getById(fincType.getId());
        if (fincType1 == null){
            return new Result(Code.ERROR, null, "不存在该数据，编辑失败");
        }
        boolean update = iFincTypeService.updateById(fincType);
        if (update) {
            return new Result(Code.OK, null, "编辑成功");
        } else {
            return new Result(Code.ERROR, null, "编辑失败");
        }
    }


    /**
     * 添加子支出类型
     * @param
     * @return
     */
    @PostMapping("/addNextFincType")
    public Result addNextFincType(@RequestBody FincType fincType) {
        FincType fincType1 = iFincTypeService.getById(fincType.getPid());
        if (fincType1 == null){
            return new Result(Code.ERROR, null, "不存在该数据，添加失败");
        }
//        if (fincType.getFincTypeScopeList() == null || fincType.getFincTypeScopeList().isEmpty()){
//            return new Result(Code.ERROR, null, "请选择管理范围");
//        }
        fincType.setId(idWorker.nextId());
        fincType.setType(2);  //支出
        fincType.setAllIds(fincType.getId() + "," + fincType.getPid());
        boolean save = iFincTypeService.save(fincType);
        if (save) {
//            for (FincTypeScope fincTypeScope : fincType.getFincTypeScopeList()){
//                fincTypeScope.setFincTypeId(fincType.getId());
//                iFincTypeScopeService.save(fincTypeScope);
//            }

            return new Result(Code.OK, null, "添加成功");
        }
      return new Result(Code.ERROR, null, "添加失败");
    }

    @DeleteMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public Result delete(@RequestBody Map reMap) {
        List<String> ids = (List<String>) reMap.get("ids");
        if (ids == null || ids.isEmpty()){
            return new Result(Code.DELETE_ERROR, "", "请选择要删除的id");
        }
        try {
            for (String id : ids){
                FincType fincType = iFincTypeService.getById(id);
                if (fincType == null){
                    return new Result(Code.DELETE_ERROR, "", "不存在该数据，删除失败");
                }
                QueryWrapper<FincType> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("pid",id);
                long count = iFincTypeService.count(queryWrapper);
                if (count > 0){
                    return new Result(Code.DELETE_ERROR, "", fincType.getName()+"已存在数据，无法删除");
                }
            }
            QueryWrapper<FincType> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("id",ids);
            iFincTypeService.remove(queryWrapper);
            //删除管理范围
//            QueryWrapper<FincTypeScope> fincTypeScopeQueryWrapper = new QueryWrapper<>();
//            fincTypeScopeQueryWrapper.in("finc_type_id",ids);
//            iFincTypeScopeService.remove(fincTypeScopeQueryWrapper);

            return new Result(Code.DELETE_OK, "", Code.DELETE_OK_MSG);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.DELETE_ERROR, "", Code.DELETE_ERROR_MSG);
        }
    }

}
